﻿#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <QObject>
#include <QTcpSocket>
#include <QHostAddress>

class TcpClient : public QObject {
    Q_OBJECT

public:
    TcpClient(QObject *parent = nullptr) : QObject(parent) {
        socket = new QTcpSocket(this);

        // 连接信号槽
        connect(socket, &QTcpSocket::connected, this, &TcpClient::onConnected);
        connect(socket, &QTcpSocket::disconnected, this, &TcpClient::onDisconnected);
        connect(socket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
    }
    ~TcpClient()
    {
        if(socket)
            socket->disconnectFromHost();
        socket->deleteLater();
        socket=nullptr;

    }
public slots:
    void connectToServer(QString addr,int port) {
        // 连接到服务器
        socket->connectToHost(addr, port);
    }

    void sendMessage(const QString &message) {
        if(!socket)
            return;
        if (socket->state() == QTcpSocket::ConnectedState) {
            socket->write(message.toUtf8());
        }
    }
    void disconnectServer()
    {
        if(socket)
            socket->disconnectFromHost();
    }
private slots:
    void onConnected() {
        emit connected();
    }

    void onDisconnected() {
        emit disconnected();
    }

    void onReadyRead() {
        // 读取服务器发送的数据
        QByteArray data = socket->readAll();
        emit messageReceived(QString::fromUtf8(data));
    }

signals:
    void messageReceived(const QString &message);
    void connected();
    void disconnected();

private:
    QTcpSocket *socket=nullptr;
};

#endif // TCPCLIENT_H
